import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Typography, Steps, Form, Select, InputNumber, Space, Radio, message, Modal, Checkbox, Tag, Spin } from 'antd';
import { 
  VideoCameraOutlined, 
  SettingOutlined, 
  RobotOutlined,
  UserOutlined,
  CheckCircleOutlined,
  ArrowLeftOutlined,
  FileTextOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { getResumes } from '../api/user';
import CameraBox from '../components/CamerBox';

const { Title, Text } = Typography;
const { Option } = Select;

const interviewTypes = [
  {
    title: '前端工程师',
    icon: <SettingOutlined style={{ fontSize: 36, color: '#5B6DFF' }} />,
    description: '专注于Web前端开发技术栈的面试模拟',
    scenarios: ['React', 'Vue', 'JavaScript', 'CSS']
  },
  {
    title: '后端工程师',
    icon: <UserOutlined style={{ fontSize: 36, color: '#5B6DFF' }} />,
    description: '后端系统开发与架构设计的深度面试',
    scenarios: ['Java', 'Go', 'Python', '微服务']
  },
  {
    title: '算法工程师',
    icon: <RobotOutlined style={{ fontSize: 36, color: '#5B6DFF' }} />,
    description: '算法与数据结构、AI方向的面试模拟',
    scenarios: ['机器学习', '深度学习', '图算法']
  },
  {
    title: '测试工程师',
    icon: <CheckCircleOutlined style={{ fontSize: 36, color: '#5B6DFF' }} />,
    description: '软件测试、自动化测试相关岗位面试',
    scenarios: ['自动化', '功能测试', '性能测试']
  },
  {
    title: '产品经理',
    icon: <SettingOutlined style={{ fontSize: 36, color: '#52C41A' }} />,
    description: '产品设计、需求分析与项目管理面试',
    scenarios: ['需求分析', '项目管理', '用户体验']
  },
  {
    title: '运维工程师',
    icon: <UserOutlined style={{ fontSize: 36, color: '#FAAD14' }} />,
    description: '系统运维、云平台与自动化运维面试',
    scenarios: ['Linux', 'Docker', 'K8s', '云计算']
  },
  {
    title: 'AI工程师',
    icon: <RobotOutlined style={{ fontSize: 36, color: '#13C2C2' }} />,
    description: '人工智能、NLP、CV等方向面试',
    scenarios: ['NLP', 'CV', '强化学习']
  },
  {
    title: '大数据工程师',
    icon: <SettingOutlined style={{ fontSize: 36, color: '#722ED1' }} />,
    description: '大数据平台、数据分析与处理面试',
    scenarios: ['Hadoop', 'Spark', '数据仓库']
  },
  {
    title: '嵌入式工程师',
    icon: <UserOutlined style={{ fontSize: 36, color: '#EB2F96' }} />,
    description: '嵌入式系统、物联网相关岗位面试',
    scenarios: ['C/C++', '单片机', '物联网']
  },
  {
    title: '移动端开发',
    icon: <RobotOutlined style={{ fontSize: 36, color: '#1890FF' }} />,
    description: 'iOS/Android移动端开发面试',
    scenarios: ['iOS', 'Android', 'Flutter']
  }
];

// 面试主界面组件
function InterviewMain({ onEnd }) {
  // 这里可根据实际业务传递props，如面试官、题目、评分等
  return (
    <div style={{ position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', zIndex: 3000, background: '#f7f8fa' }}>
      {/* 左右分栏布局 */}
      <div style={{ display: 'flex', height: '100%' }}>
        {/* 左侧对话区 */}
        <div style={{ flex: 1, position: 'relative', background: '#fff', borderRight: '1px solid #f0f0f0', display: 'flex', flexDirection: 'column' }}>
          {/* 摄像头悬浮窗口 */}
          <CameraBox />
          {/* 聊天内容区（可替换为实际聊天组件） */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '80px 24px 24px 24px' }}>
            {/* 聊天内容示例 */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="面试官" style={{ width: 40, height: 40, borderRadius: '50%', marginRight: 12 }} />
                <div>
                  <div style={{ fontWeight: 500 }}>王梓晨 <span style={{ color: '#888', fontSize: 12 }}>资深前端技术面试官</span></div>
                  <div style={{ color: '#aaa', fontSize: 12 }}>14:30:25</div>
                </div>
              </div>
              <div style={{ background: '#f5f7fa', borderRadius: 8, padding: 12, marginLeft: 52, maxWidth: 420 }}>
                你好！我是今天的面试官王梓晨。首先请你简单介绍一下自己的技术背景和项目经验。
              </div>
            </div>
            <div style={{ marginBottom: 24, textAlign: 'right' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginBottom: 8 }}>
                <div>
                  <div style={{ fontWeight: 500, textAlign: 'right' }}>陈思远</div>
                  <div style={{ color: '#aaa', fontSize: 12, textAlign: 'right' }}>14:30:45</div>
                </div>
                <img src="https://randomuser.me/api/portraits/women/44.jpg" alt="用户" style={{ width: 40, height: 40, borderRadius: '50%', marginLeft: 12 }} />
              </div>
              <div style={{ background: '#e6f7ff', borderRadius: 8, padding: 12, marginRight: 52, maxWidth: 420, display: 'inline-block' }}>
                您好！我叫陈思远，是一名有5年工作经验的前端开发工程师。我目前主要使用 React 技术栈进行开发，对现代前端工程化和性能优化有较深的理解...
              </div>
            </div>
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="面试官" style={{ width: 40, height: 40, borderRadius: '50%', marginRight: 12 }} />
                <div>
                  <div style={{ fontWeight: 500 }}>王梓晨 <span style={{ color: '#888', fontSize: 12 }}>资深前端技术面试官</span></div>
                  <div style={{ color: '#aaa', fontSize: 12 }}>14:31:10</div>
                </div>
              </div>
              <div style={{ background: '#f5f7fa', borderRadius: 8, padding: 12, marginLeft: 52, maxWidth: 420 }}>
                好的。那么请你详细讲解一下 React 中的虚拟 DOM 原理，以及它在性能优化方面的作用。
              </div>
            </div>
          </div>
          {/* 输入区 */}
          <div style={{ borderTop: '1px solid #f0f0f0', padding: 16, background: '#fafbfc', display: 'flex', alignItems: 'center' }}>
            <input placeholder="请输入你的回答..." style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, background: 'transparent' }} />
            <Button type="primary" style={{ marginLeft: 16 }}>发送</Button>
          </div>
        </div>
        {/* 右侧评分与进度区 */}
        <div style={{ width: 320, background: '#fff', padding: 24, display: 'flex', flexDirection: 'column', borderLeft: '1px solid #f0f0f0' }}>
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontWeight: 500, fontSize: 16, marginBottom: 8 }}>面试进度 <span style={{ color: '#1890ff', fontSize: 14, marginLeft: 8 }}>2/15题</span></div>
            <div style={{ height: 6, background: '#f0f0f0', borderRadius: 3, overflow: 'hidden', marginBottom: 8 }}>
              <div style={{ width: '13%', height: '100%', background: '#1890ff' }} />
            </div>
          </div>
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontWeight: 500, fontSize: 16, marginBottom: 16 }}>实时评分</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
              <div style={{ width: 140, background: '#f5f7fa', borderRadius: 8, padding: 12, marginBottom: 8 }}>
                <div style={{ color: '#888', fontSize: 13 }}>专业知识</div>
                <div style={{ fontWeight: 600, fontSize: 22, color: '#1890ff' }}>92</div>
              </div>
              <div style={{ width: 140, background: '#f5f7fa', borderRadius: 8, padding: 12, marginBottom: 8 }}>
                <div style={{ color: '#888', fontSize: 13 }}>表达能力</div>
                <div style={{ fontWeight: 600, fontSize: 22, color: '#1890ff' }}>88</div>
              </div>
              <div style={{ width: 140, background: '#f5f7fa', borderRadius: 8, padding: 12, marginBottom: 8 }}>
                <div style={{ color: '#888', fontSize: 13 }}>逻辑思维</div>
                <div style={{ fontWeight: 600, fontSize: 22, color: '#1890ff' }}>90</div>
              </div>
              <div style={{ width: 140, background: '#f5f7fa', borderRadius: 8, padding: 12, marginBottom: 8 }}>
                <div style={{ color: '#888', fontSize: 13 }}>综合得分</div>
                <div style={{ fontWeight: 600, fontSize: 22, color: '#1890ff' }}>90</div>
              </div>
            </div>
          </div>
          <Button type="primary" danger style={{ marginBottom: 16 }} onClick={onEnd}>结束面试</Button>
          <Button>暂停面试</Button>
        </div>
      </div>
    </div>
  );
}

export default function Interview() {
  const [currentStep, setCurrentStep] = useState(0);
  const [selectedPosition, setSelectedPosition] = useState(null);
  const [interviewConfig, setInterviewConfig] = useState({
    duration: 30,
    difficulty: 'medium',
    topics: [],
    resumeId: ''
  });
  const [resumes, setResumes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [topicModalVisible, setTopicModalVisible] = useState(false);
  const [selectedTopics, setSelectedTopics] = useState([]);
  const [resumeModalVisible, setResumeModalVisible] = useState(false);
  const [envLoading, setEnvLoading] = useState(false);
  const [envReady, setEnvReady] = useState(false);

  // 获取用户简历列表
  useEffect(() => {
    if (currentStep === 1) {
      fetchResumes();
    }
  }, [currentStep]);

  const fetchResumes = async () => {
    setLoading(true);
    try {
      const res = await getResumes(1, 10);
      if (res.success) {
        setResumes(res.data.records || []);
        // 如果有默认简历，自动选择
        const defaultResume = res.data.records?.find(r => r.default);
        if (defaultResume) {
          setInterviewConfig(prev => ({ ...prev, resumeId: defaultResume.id }));
        }
      } else {
        message.error(res.message || '获取简历失败');
      }
    } catch (error) {
      message.error('获取简历失败');
    } finally {
      setLoading(false);
    }
  };

  const handleStartInterview = (position) => {
    setSelectedPosition(position);
    setCurrentStep(1);
  };

  const handleConfigSubmit = (values) => {
    if (selectedTopics.length === 0) {
      message.error('请至少选择一个面试主题');
      return;
    }
    if (!interviewConfig.resumeId) {
      message.error('请选择简历');
      return;
    }
    
    setInterviewConfig(prev => ({ ...prev, topics: selectedTopics }));
    setCurrentStep(2);
  };

  const handleBackToStep1 = () => {
    setCurrentStep(0);
    setSelectedPosition(null);
    setSelectedTopics([]);
  };

  const handleBackToStep2 = () => {
    setCurrentStep(1);
  };

  const handleStartRealInterview = () => {
    setEnvLoading(true);
    setTimeout(() => {
      setEnvLoading(false);
      setEnvReady(true);
    }, 1800); // 1.8秒后进入主界面，实际可用接口回调
  };

  const handleTopicSelect = (topic) => {
    setSelectedTopics(prev => {
      if (prev.includes(topic)) {
        return prev.filter(t => t !== topic);
      } else {
        return [...prev, topic];
      }
    });
  };

  const handleTopicModalOk = () => {
    setTopicModalVisible(false);
  };

  const handleTopicModalCancel = () => {
    setTopicModalVisible(false);
  };

  const handleResumeSelect = (resumeId) => {
    setInterviewConfig(prev => ({ ...prev, resumeId }));
    setResumeModalVisible(false);
  };

  const handleResumeModalOk = () => {
    setResumeModalVisible(false);
  };

  const handleResumeModalCancel = () => {
    setResumeModalVisible(false);
  };

  // 退出面试主界面
  const handleEndInterview = () => {
    setEnvReady(false);
    setCurrentStep(0);
    setSelectedPosition(null);
    setInterviewConfig({ duration: 30, difficulty: 'medium', topics: [], resumeId: '' });
    setSelectedTopics([]);
  };

  // 第一步：选择岗位
  const renderStep1 = () => (
        <Row gutter={[24, 24]}>
          {interviewTypes.map((type, index) => (
            <Col xs={24} sm={12} md={8} key={index}>
              <Card
                hoverable
                style={{ height: '100%' }}
                actions={[
              <Button 
                type="primary" 
                icon={<VideoCameraOutlined />}
                onClick={() => handleStartInterview(type)}
              >
                    开始面试
                  </Button>
                ]}
              >
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                  {type.icon}
                  <Title level={4} style={{ marginTop: 16 }}>{type.title}</Title>
                </div>
                <Text type="secondary">{type.description}</Text>
                <div style={{ marginTop: 16 }}>
                  {type.scenarios.map((scenario, idx) => (
                    <Text key={idx} style={{ marginRight: 8 }}>
                      <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 4 }} />
                      {scenario}
                    </Text>
                  ))}
                </div>
              </Card>
            </Col>
          ))}
        </Row>
  );

  // 第二步：场景配置
  const renderStep2 = () => (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Text strong>已选择岗位：</Text>
        <Text type="primary" style={{ marginLeft: 8 }}>{selectedPosition?.title}</Text>
      </div>
      
      <Form
        layout="vertical"
        onFinish={handleConfigSubmit}
        initialValues={interviewConfig}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          label="面试时长（分钟）"
          name="duration"
          rules={[{ required: true, message: '请选择面试时长' }]}
        >
          <Select>
            <Option value={15}>15分钟</Option>
            <Option value={30}>30分钟</Option>
            <Option value={45}>45分钟</Option>
            <Option value={60}>60分钟</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="难度等级"
          name="difficulty"
          rules={[{ required: true, message: '请选择难度等级' }]}
        >
          <Select>
            <Option value="easy">初级</Option>
            <Option value="medium">中级</Option>
            <Option value="hard">高级</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="面试主题"
          required
        >
          <div 
            style={{ 
              border: '1px solid #d9d9d9', 
              borderRadius: 6, 
              padding: '8px 12px', 
              cursor: 'pointer',
              minHeight: 32,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between'
            }}
            onClick={() => setTopicModalVisible(true)}
          >
            <div style={{ flex: 1 }}>
              {selectedTopics.length > 0 ? (
                <div>
                  {selectedTopics.map((topic, index) => (
                    <Tag key={index} color="blue" style={{ marginBottom: 4 }}>
                      {topic}
                    </Tag>
                  ))}
                </div>
              ) : (
                <Text type="secondary">请选择面试主题</Text>
              )}
            </div>
            <PlusOutlined style={{ color: '#999' }} />
          </div>
        </Form.Item>

        <Form.Item
          label="选择简历"
          required
        >
          <div 
            style={{ 
              border: '1px solid #d9d9d9', 
              borderRadius: 6, 
              padding: '8px 12px', 
              cursor: 'pointer',
              minHeight: 32,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between'
            }}
            onClick={() => setResumeModalVisible(true)}
          >
            <div style={{ flex: 1 }}>
              {interviewConfig.resumeId ? (
                <Space>
                  <FileTextOutlined />
                  <Text>{resumes.find(r => r.id === interviewConfig.resumeId)?.filename}</Text>
                  {resumes.find(r => r.id === interviewConfig.resumeId)?.default && (
                    <Text type="secondary" style={{ fontSize: 12 }}>(默认简历)</Text>
                  )}
                </Space>
              ) : (
                <Text type="secondary">请选择简历</Text>
              )}
            </div>
            <FileTextOutlined style={{ color: '#999' }} />
          </div>
        </Form.Item>

        {resumes.length === 0 && (
          <div style={{ marginBottom: 16, padding: 16, background: '#f5f5f5', borderRadius: 6 }}>
            <Text type="secondary">
              <FileTextOutlined style={{ marginRight: 8 }} />
              您还没有上传简历，请先上传简历后再开始面试
            </Text>
          </div>
        )}

        <Form.Item>
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={handleBackToStep1}>
              返回选择岗位
            </Button>
            <Button 
              type="primary" 
              htmlType="submit"
              disabled={resumes.length === 0}
            >
              下一步
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 面试主题选择弹窗 */}
      <Modal
        title="选择面试主题"
        open={topicModalVisible}
        onOk={handleTopicModalOk}
        onCancel={handleTopicModalCancel}
        width={500}
      >
        <div style={{ maxHeight: 300, overflowY: 'auto' }}>
          {selectedPosition?.scenarios.map((scenario, index) => (
            <div key={index} style={{ marginBottom: 12 }}>
              <Checkbox
                checked={selectedTopics.includes(scenario)}
                onChange={() => handleTopicSelect(scenario)}
              >
                {scenario}
              </Checkbox>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16, padding: 12, background: '#f5f5f5', borderRadius: 6 }}>
          <Text type="secondary">
            已选择 {selectedTopics.length} 个主题
          </Text>
        </div>
      </Modal>

      {/* 简历选择弹窗 */}
      <Modal
        title="选择简历"
        open={resumeModalVisible}
        onOk={handleResumeModalOk}
        onCancel={handleResumeModalCancel}
        width={500}
        footer={null}
      >
        <div style={{ maxHeight: 400, overflowY: 'auto' }}>
          {resumes.length > 0 ? (
            resumes.map((resume) => (
              <div 
                key={resume.id} 
                style={{ 
                  padding: 12, 
                  border: '1px solid #d9d9d9', 
                  borderRadius: 6, 
                  marginBottom: 8,
                  cursor: 'pointer',
                  backgroundColor: interviewConfig.resumeId === resume.id ? '#e6f7ff' : '#fff',
                  borderColor: interviewConfig.resumeId === resume.id ? '#1890ff' : '#d9d9d9'
                }}
                onClick={() => handleResumeSelect(resume.id)}
              >
                <Space>
                  <FileTextOutlined style={{ color: '#1890ff' }} />
                  <Text strong>{resume.filename}</Text>
                  {resume.default && (
                    <Tag color="blue" size="small">默认简历</Tag>
                  )}
                </Space>
                {interviewConfig.resumeId === resume.id && (
                  <CheckCircleOutlined 
                    style={{ 
                      float: 'right', 
                      color: '#52c41a', 
                      fontSize: 16 
                    }} 
                  />
                )}
              </div>
            ))
          ) : (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <FileTextOutlined style={{ fontSize: 48, color: '#d9d9d9', marginBottom: 16 }} />
              <Text type="secondary">暂无简历，请先上传简历</Text>
            </div>
          )}
        </div>
      </Modal>
    </div>
  );

  // 第三步：准备就绪
  const renderStep3 = () => {
    const selectedResume = resumes.find(r => r.id === interviewConfig.resumeId);
    
    return (
      <div style={{ textAlign: 'center', padding: '40px 0' }}>
        <div style={{ marginBottom: 32 }}>
          <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a', marginBottom: 16 }} />
          <Title level={3}>面试配置完成</Title>
        </div>

        <Card style={{ maxWidth: 600, margin: '0 auto', marginBottom: 32 }}>
          <Row gutter={24}>
            <Col span={12}>
              <div>
                <Text type="secondary">岗位</Text>
                <div><Text strong>{selectedPosition?.title}</Text></div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text type="secondary">时长</Text>
                <div><Text strong>{interviewConfig.duration}分钟</Text></div>
              </div>
            </Col>
          </Row>
          <Row gutter={24} style={{ marginTop: 16 }}>
            <Col span={12}>
              <div>
                <Text type="secondary">难度</Text>
                <div><Text strong>
                  {interviewConfig.difficulty === 'easy' ? '初级' : 
                   interviewConfig.difficulty === 'medium' ? '中级' : '高级'}
                </Text></div>
              </div>
            </Col>
            <Col span={12}>
              <div>
                <Text type="secondary">主题</Text>
                <div>
                  {interviewConfig.topics.map((topic, index) => (
                    <Tag key={index} color="blue" style={{ marginBottom: 4 }}>
                      {topic}
                    </Tag>
                  ))}
                </div>
              </div>
            </Col>
          </Row>
          <Row gutter={24} style={{ marginTop: 16 }}>
            <Col span={24}>
              <div>
                <Text type="secondary">简历</Text>
                <div><Text strong>{selectedResume?.filename}</Text></div>
              </div>
            </Col>
          </Row>
        </Card>

        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={handleBackToStep2}>
            返回配置
          </Button>
          <Button 
            type="primary" 
            size="large" 
            icon={<VideoCameraOutlined />}
            onClick={handleStartRealInterview}
          >
            开始面试
          </Button>
        </Space>
      </div>
    );
  };

  return (
    <div>
      {envLoading && (
        <div style={{ position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', background: 'rgba(255,255,255,0.95)', zIndex: 2000, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <Spin size="large" style={{ marginBottom: 24 }} />
          <div style={{ fontSize: 20, color: '#1890ff', fontWeight: 500, marginBottom: 8 }}>面试环境加载中，请稍等</div>
          <div style={{ color: '#888' }}>预计1~2分钟</div>
        </div>
      )}
      {envReady ? (
        <InterviewMain onEnd={handleEndInterview} />
      ) : (
        <Card>
          <Title level={4}>开始面试</Title>
          <Text type="secondary" style={{ marginBottom: 24, display: 'block' }}>
            选择您想要进行的面试类型，我们将为您提供专业的面试模拟体验
          </Text>

          <Steps
            current={currentStep}
            items={[
              { title: '选择岗位', description: '选择目标职位' },
              { title: '场景配置', description: '设置面试参数' },
              { title: '准备就绪', description: '开始面试' },
            ]}
            style={{ marginBottom: 48 }}
          />

          {currentStep === 0 && renderStep1()}
          {currentStep === 1 && renderStep2()}
          {currentStep === 2 && renderStep3()}
        </Card>
      )}
    </div>
  );
} 